<template>
  <div class="boyi-customer-container">
    <vab-query-form>
      <el-row>
        <el-col :span="20">
          <el-form :inline="true" :model="queryForm" @submit.prevent>
            <el-space wrap size="small">
              <el-form-item>
                <el-select
                  v-model="queryForm.tag"
                  multiple
                  filterable
                  placeholder="标签"
                >
                  <el-option
                    v-for="item in tag_list"
                    :key="item.id"
                    :label="item.tag_name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-date-picker
                  v-model="queryForm.daterange"
                  type="daterange"
                  date-format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                />
              </el-form-item>
              <el-form-item>
                <el-select
                  v-model="queryForm.institutionId"
                  clearable
                  filterable
                  placeholder="请选择机构"
                >
                  <el-option
                    v-for="(item, index) in institutionList"
                    :key="index"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-cascader
                  v-model="queryForm.progress_data"
                  clearable
                  :options="clueStatusOptions"
                  :props="{ expandTrigger: 'hover', multiple: true }"
                  placeholder="论文进程"
                />
              </el-form-item>
              <el-form-item>
                <el-select
                  v-model="queryForm.schoolCode"
                  clearable
                  filterable
                  placeholder="请选择学校"
                >
                  <el-option
                    v-for="(item, index) in schoolList"
                    :key="index"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-input
                  v-model.trim="queryForm.name"
                  clearable
                  placeholder="请输入姓名"
                />
              </el-form-item>
              <el-form-item>
                <el-input
                  v-model.trim="queryForm.clue"
                  clearable
                  placeholder="请输入选题"
                />
              </el-form-item>
              <el-form-item>
                <el-input
                  v-model.trim="queryForm.zhuanye"
                  clearable
                  placeholder="专业"
                />
              </el-form-item>
            </el-space>
          </el-form>
        </el-col>
        <el-col :span="4" style="text-align: right">
          <el-button :icon="Search" type="primary" @click="queryData">
            查询
          </el-button>
          <el-button :icon="Plus" type="primary" @click="handleEdit">
            添加
          </el-button>

          <!-- <el-button :icon="Delete" type="danger" @click="handleDelete">
            批量删除
          </el-button> -->
        </el-col>
      </el-row>
    </vab-query-form>

    <el-table
      v-loading="listLoading"
      :data="list"
      size="small"
      highlight-current-row
      @selection-change="setSelectRows"
    >
      <!-- <el-table-column type="expand">xxx</el-table-column> -->
      <el-table-column align="center" show-overflow-tooltip type="selection" />

      <el-table-column
        align="center"
        label="id"
        prop="id"
        show-overflow-tooltip
        width="50"
      />

      <el-table-column
        align="center"
        label="机构"
        prop="institution.name"
        show-overflow-tooltip
        width="100"
      />

      <el-table-column
        align="center"
        label="学生名字"
        prop="name"
        show-overflow-tooltip
        width="100"
      />

      <el-table-column
        align="center"
        label="学校"
        prop="school.name"
        show-overflow-tooltip
        width="130"
      />
      <el-table-column
        align="center"
        label="层次"
        prop="cengci"
        show-overflow-tooltip
        width="100"
      />
      <el-table-column
        align="center"
        label="学位"
        prop="school.need_xuewei"
        show-overflow-tooltip
        width="100"
      >
        <template #default="scope">
          {{ scope.row.need_xuewei == '1' ? '需要' : '不需要' }}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="专业"
        prop="zhuanye"
        show-overflow-tooltip
        width="130"
      />
      <el-table-column
        align="center"
        label="选题"
        prop="clue"
        show-overflow-tooltip
        width="200"
      />
      <el-table-column
        align="center"
        label="字数"
        prop="word_num"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        label="查重率"
        prop="word_num"
        show-overflow-tooltip
        width="100"
      >
        <template #default="scope">
          {{ scope.row.chachong_ruanjian }}/{{ scope.row.chachonglv }}
        </template>
      </el-table-column>

      <el-table-column
        align="center"
        label="任务进度"
        prop="clue"
        show-overflow-tooltip
        width="200"
      >
        <template #default="scope">
          <el-tooltip
            v-for="(item, index) in scope.row.job_list"
            :key="index"
            class="item"
            effect="dark"
            :content="item.name + ':' + item.job_status_info.info"
            placement="top"
          >
            <el-badge
              :is-dot="item.is_my_job || item.is_my_publish_job"
              class="item"
              type="danger"
            >
              <el-button
                :type="item.job_status_info.button_type"
                size="small"
                :circle="true"
                @click="progressClick(scope.row, item)"
              >
                {{ item.short_name }}
              </el-button>
            </el-badge>
          </el-tooltip>
        </template>
      </el-table-column>

      <el-table-column align="center" label="截止时间" width="100">
        <template #default="{ row }">
          <el-tag
            :title="row.died_line_time_str"
            :type="row.died_line_info.tag_type"
            size="small"
          >
            {{ row.died_line_info.str }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        v-permissions="['Admin', 'Jiaowu']"
        align="center"
        label="成交价"
        prop="amount"
        show-overflow-tooltip
        width="100"
      />
      <el-table-column
        v-permissions="['Admin', 'Jiaowu']"
        align="center"
        label="已收款"
        prop="received_amount"
        show-overflow-tooltip
        width="100"
      />
      <el-table-column
        v-permissions="['Admin', 'Jiaowu']"
        align="center"
        label="未收"
        prop="clue"
        show-overflow-tooltip
      >
        <template #default="scope">
          <el-tooltip
            class="item"
            effect="dark"
            :content="
              '成交价：' +
              scope.row.amount +
              '元，' +
              '已收：' +
              scope.row.received_amount +
              '元，' +
              '待收：' +
              (scope.row.amount - scope.row.received_amount) +
              '元'
            "
            placement="top"
          >
            <el-tag
              :type="
                scope.row.amount - scope.row.received_amount > 0
                  ? 'danger'
                  : 'success'
              "
              size="small"
            >
              {{ scope.row.amount - scope.row.received_amount }}
            </el-tag>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column prop="clue_report" label="标签" width="100">
        <template #default="scope">
          <el-tag
            v-for="(tag, index) in scope.row.tag_list"
            :key="index"
            closable
            size="mini"
            :disable-transitions="false"
            @close="handleDelObjTagRel(scope.row, tag)"
          >
            {{ tag.tag_name }}
          </el-tag>
          <el-tag size="mini" @click="addTag(scope.row)">+标签</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="是否上传"
        prop="clue"
        show-overflow-tooltip
      >
        <template #default="scope">
          <el-popover
            v-if="scope.row.is_upload_system"
            placement="bottom"
            title="系统上传单"
            :width="300"
            trigger="click"
          >
            <template #reference>
              <el-tag
                :type="scope.row.is_upload_system ? 'success' : 'info'"
                size="small"
              >
                {{ scope.row.is_upload_system ? '是' : '否' }}
              </el-tag>
            </template>
            上传地址：
            <a :href="scope.row.login_url" target="_blank">
              {{ scope.row.login_url }}
            </a>
            <br />
            上传账号：{{ scope.row.login_username }}
            <br />
            上传密码：{{ scope.row.login_password }}
          </el-popover>
          <el-tag v-else type="info" size="small">
            {{ scope.row.is_upload_system ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="创建时间"
        prop="create_time"
        show-overflow-tooltip
        width="110"
      />
      <el-table-column fixed="right" align="center" label="操作" width="200">
        <template #default="{ row }">
          <el-button-group>
            <el-button
              v-permissions="['Jiaowu', 'Admin']"
              text
              size="small"
              @click="addFinances(row)"
            >
              收支
            </el-button>
            <el-button text size="small" @click="handleAssignJob(row)">
              指派任务
            </el-button>

            <el-dropdown v-permissions="['Admin', 'Jiaowu']" trigger="click">
              <el-button text size="small">更多</el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item class="clearfix" @click="handleEdit(row)">
                    编辑
                  </el-dropdown-item>
                  <el-dropdown-item class="clearfix" @click="handleDelete(row)">
                    删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      :current-page="queryForm.pageNo"
      :layout="layout"
      :page-size="queryForm.pageSize"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />
    <edit
      ref="editRef"
      :school-list="schoolList"
      :institution-list="institutionList"
      @fetch-data="fetchData"
    />
    <assign-job
      ref="assignJobRef"
      :job-type-list="jobTypeList"
      :user-list="userList"
      @fetch-data="fetchData"
    />
    <job-handle ref="jobHandle" @fetch-data="fetchData" />
    <add-finances ref="addFinancesRef" @fetch-data="fetchData" />
    <add-tag ref="addTagRef" :taglist="tag_list" @fetch-data="fetchData" />
  </div>
</template>

<script>
  import { getList, doDelete } from '@/api/boyiCustomer'
  import { getCustomerConfig } from '@/api/config'
  import { delObjTagRel } from '@/api/boyiTag'
  import Edit from './components/BoyiCustomerEdit'
  import AssignJob from './components/AssignJob'
  import JobHandle from '@/views/boyi/job/components/JobHandle'
  import AddFinances from './components/AddFinances'
  import AddTag from './components/AddTag'
  import { Delete, Plus, Search } from '@element-plus/icons-vue'
  import { useRoute } from 'vue-router'

  export default defineComponent({
    name: 'CustomerIndex',
    components: { Edit, AssignJob, JobHandle, AddFinances, AddTag },

    setup() {
      const $baseConfirm = inject('$baseConfirm')
      const $baseMessage = inject('$baseMessage')

      const route = useRoute()
      console.log(route)
      console.log('-------------')

      const state = reactive({
        editRef: null,
        addTagRef: null,
        assignJobRef: null,
        addFinancesRef: null,
        jobHandle: null,
        list: [],
        listLoading: true,
        schoolList: [],
        clueStatus: '',
        clueStatusOptions: [],
        institutionList: [],
        jobTypeList: [],
        userList: [],
        tag_list: [],
        layout: 'total, sizes, prev, pager, next, jumper',
        total: 0,
        selectRows: '',
        route: {},
        queryForm: {
          pageNo: 1,
          pageSize: 10,
          title: '',
          institutionId: '',
          zhuanye: '',
          progress_data: [],
        },
      })

      const handleQuery = () => {
        state.route = {
          path: route.path,
          query: route.query,
          name: route.name,
          meta: route.meta,
        }
      }

      const setSelectRows = (val) => {
        state.selectRows = val
      }

      const progressClick = (row, item) => {
        state.jobHandle.showEdit(row, item)
      }
      const handleEdit = (row) => {
        if (row.id) {
          state.editRef.showEdit(row)
        } else {
          state.editRef.showEdit()
        }
      }
      const addTag = (row) => {
        if (row.id) {
          state.addTagRef.showEdit(row)
        } else {
          state.addTagRef.showEdit()
        }
      }
      const handleAssignJob = (row) => {
        state.assignJobRef.showEdit(row)
      }
      const addFinances = (row) => {
        state.addFinancesRef.showEdit(row)
      }
      const handleDelete = (row) => {
        if (row.id) {
          $baseConfirm('你确定要删除当前项吗', null, async () => {
            const { msg } = await doDelete({ ids: row.id })
            $baseMessage(msg, 'success', 'vab-hey-message-success')
            await fetchData()
          })
        } else {
          if (state.selectRows.length > 0) {
            const ids = state.selectRows.map((item) => item.id).join()
            $baseConfirm('你确定要删除选中项吗', null, async () => {
              const { msg } = await doDelete({ ids })
              $baseMessage(msg, 'success', 'vab-hey-message-success')
              await fetchData()
            })
          } else {
            $baseMessage('未选中任何行', 'error', 'vab-hey-message-error')
          }
        }
      }
      const handleSizeChange = (val) => {
        state.queryForm.pageSize = val
        fetchData()
      }
      const handleCurrentChange = (val) => {
        state.queryForm.pageNo = val
        fetchData()
      }
      const queryData = () => {
        state.queryForm.pageNo = 1
        fetchData()
      }
      const fetchData = async () => {
        state.listLoading = true
        state.queryForm = {
          ...state.queryForm,
          ...state.route.query,
        }
        const {
          data: { list, total },
        } = await getList(state.queryForm)
        state.list = list
        state.total = total
        state.listLoading = false
      }

      // const fetchSchoolData = async () => {
      //   const {
      //     data: { list },
      //   } = await getListFromSchool()
      //   state.schoolList = list
      // }

      // const fetchInstitutionData = async () => {
      //   const {
      //     data: { list },
      //   } = await getListFromInstitution()
      //   state.institutionList = list
      // }
      // const fetchJobTypeData = async () => {
      //   const {
      //     data: { list },
      //   } = await getListFromJobType()
      //   state.jobTypeList = list
      // }
      const getCustomerConfigData = async () => {
        const {
          data: {
            institutionList,
            schoolList,
            jobTypeList,
            tag_list,
            userList,
            progress_data,
          },
        } = await getCustomerConfig()
        state.institutionList = institutionList
        state.schoolList = schoolList
        state.tag_list = tag_list
        state.jobTypeList = jobTypeList
        state.userList = userList
        state.clueStatusOptions = progress_data
      }
      // const getUserListData = async () => {
      //   const {
      //     data: { list },
      //   } = await getUserList()
      //   state.userList = list
      // }
      const handleDelObjTagRel = async (customer, tag) => {
        console.log(tag)
        await $baseConfirm('你确定要删除当前标签吗', null, async () => {
          const { msg } = await delObjTagRel({
            obj_id: customer.id,
            tag_id: tag.pivot.tag_id,
            obj_type: tag.pivot.obj_type,
          })
          $baseMessage(msg, 'success', 'vab-hey-message-success')
          await fetchData()
        })
      }

      onMounted(() => {
        handleQuery()
        fetchData()
        getCustomerConfigData()
        // fetchInstitutionData()
        // fetchJobTypeData()
        // getUserListData()
      })

      return {
        ...toRefs(state),
        setSelectRows,
        handleAssignJob,
        handleEdit,
        addFinances,
        handleDelObjTagRel,
        addTag,
        handleDelete,
        handleSizeChange,
        handleCurrentChange,
        queryData,
        fetchData,
        progressClick,
        Delete,
        Plus,
        Search,
      }
    },
  })
</script>

<style>
  .item {
    margin-top: 15px;
    margin-right: 5px;
  }
</style>
